<template>
  <div class="chart">
    <div class="label">{{ val }}<span v-if="isshowprecent">%</span></div>
    <div class="pie-wrap" ref="pie"></div>
    <h3>{{ title }}</h3>
  </div>
</template>

<script>
// 引入 ECharts 主模块
import echarts from "echarts/lib/echarts";
// 引入柱状图
require("echarts/lib/chart/pie");
// 引入提示框和标题组件
require("echarts/lib/component/tooltip");
require("echarts/lib/component/title");

export default {
  name: "chart",
  props: {
    title: { type: String, required: true },
    val: { type: Number, required: true },
    isshowprecent: { type: Boolean, required: true, default: false }
  },
  data() {
    return {};
  },
  mounted() {
    this.initChart();
  },
  watch: {
    val: function() {
      this.initChart();
    }
  },
  components: {},
  methods: {
    initChart() {
      let data = [];
      if (this.isshowprecent) {
        // 显示百分比
        data.push({
          value: this.val,
          name: ""
        });
        data.push({
          value: 100 - this.val,
          name: ""
        });
      } else {
        // 不显示百分比
        data.push({
          value: 0,
          name: ""
        });
        data.push({
          value: this.val,
          name: ""
        });
      }
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(this.$refs.pie);
      myChart.setOption({
        series: [
          {
            name: this.title,
            type: "pie",
            color: ["rgb(102, 208, 113)", "rgb(223, 223, 223)"],
            radius: ["95%", "100%"],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: "center"
              },
              emphasis: {
                show: true,
                textStyle: {
                  fontSize: "30",
                  fontWeight: "bold"
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data
          }
        ]
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@mixin hwwrap {
  width: px2rem(175);
  height: px2rem(175);
}
.chart {
  position: relative;
  text-align: center;
  color: #000;

  .label {
    line-height: px2rem(175);
    position: absolute;
    @include hwwrap;
    left: 0;
    top: 0;
    font-size: px2rem(48);
    span {
      vertical-align: super;
      font-size: $text-size-small;
    }
  }
  h3 {
    font-size: $text-size;
    padding: px2rem(27) 0 px2rem(52);
    line-height: $text-size;
  }
  .pie-wrap {
    @include hwwrap;
  }
}
</style>
